﻿using ProjectCloth.Entity;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class SalesBook : UserControl
    {
        private ClothContext db = new ClothContext();
        private List<Product> products = new List<Product>();
        public SalesBook()
        {
            InitializeComponent();
            products = db.Products.ToList();
        }
        public List<SaleStatisticsModel> GetList()
        {
            var startTime = startDatePiker.Value.Date;
            var endTime = endDatePicker.Value.AddDays(1).Date;
            //var productList = db.Products.ToList();
            dataGridView1.AutoGenerateColumns = false;
            var sql = from item in (
                      from s in db.SaleOrderItems
                      join so in db.SaleOrders
                      on s.OrderId equals so.Id //into soo //  from soos in soo.DefaultIfEmpty()
                      join pro in db.Products on s.ProductId equals pro.Id
                      select new
                      {
                          s.ProductId,
                          s.OrderId,
                          s.OrderNo,
                          s.Quantity,
                          s.Amount,
                          so.InMoneyDate,
                          pro.ProductNo
                      }
                       ).Where(p => ((p.InMoneyDate > startTime && p.InMoneyDate < endTime)
                       && (string.IsNullOrEmpty(orderNoTxt.Text) || p.OrderNo.Contains(orderNoTxt.Text.ToUpper())))
                       ).ToList()
                      group item by item.ProductId into g
                      select new SaleStatisticsModel
                      {
                          ProductId = g.Key,
                          ProductNo = g.Select(o => o.ProductNo).FirstOrDefault(),
                          Frequency = g.Where(o=>!o.OrderNo.EndsWith("T")).Select(o => o.OrderNo).Distinct().Count()- g.Where(o => o.OrderNo.EndsWith("T")).Select(o => o.OrderNo).Distinct().Count(),
                          Quantity = g.Where(o => !o.OrderNo.EndsWith("T")).Sum(o => o.Quantity) - g.Where(o => o.OrderNo.EndsWith("T")).Sum(o => o.Quantity),
                          Amount = g.Where(o => !o.OrderNo.EndsWith("T")).Sum(o => o.Amount)- g.Where(o => o.OrderNo.EndsWith("T")).Sum(o => o.Amount),
                          AvgPrice = g.Where(o => !o.OrderNo.EndsWith("T")).Sum(o => o.Quantity) > 0 ? Math.Round((g.Where(o => !o.OrderNo.EndsWith("T")).Sum(o => o.Amount) - g.Where(o => o.OrderNo.EndsWith("T")).Sum(o => o.Amount)/ g.Where(o => !o.OrderNo.EndsWith("T")).Sum(o => o.Quantity) - g.Where(o => o.OrderNo.EndsWith("T")).Sum(o => o.Quantity)), 2) : 0,
                      };
            var list = sql.ToList();
            var zerolist = (from p in products
                            select new SaleStatisticsModel
                            {
                                ProductId = p.Id,
                                ProductNo = p.ProductNo,
                                Frequency = 0,
                                Quantity = 0,
                                Amount = 0,
                                AvgPrice = 0,
                            }).ToList();
            zerolist.ForEach(o =>
            {
                if (list.Count(p => p.ProductNo == o.ProductNo) == 0) list.Add(o);
            });
            return list.OrderBy(o=>o.ProductNo).ToList();
        }
        private void searchBtn_Click(object sender, EventArgs e)
        {
            var list = GetList();
            dataGridView1.DataSource = list;
            quanlitySumTxt.Text = list.Sum(o => o.Quantity).ToString();
            saleSumTxt.Text = list.Sum(o => o.Amount).ToString();

        }

        private void dataGridView1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = GetList();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                if (column.Name == "ProductNo")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.ProductNo).ToList();

                }
                else if (column.Name == "Quantity")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Quantity).ToList();
                }
                else if (column.Name == "AvgPrice")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.AvgPrice).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Amount).ToList();
                }
                else if (column.Name == "Frequency")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Frequency).ToList();
                }
            }
        }

        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = GetList();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                if (column.Name == "ProductNo")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.ProductNo).ToList();
                }
                else if (column.Name == "Quantity")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Quantity).ToList();
                }
                else if (column.Name == "AvgPrice")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.AvgPrice).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Amount).ToList();
                }
                else if (column.Name == "Frequency")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Frequency).ToList();
                }
            }

        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView1.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void exportbtn_Click(object sender, EventArgs e)
        {
            Helper.ExportDgv(dataGridView1, "销售统计");
        }
    }
    public class SaleStatisticsModel
    {
        public int ProductId { get; set; }
        public string ProductNo { get; set; }
        public decimal Frequency { get; set; }
        public decimal Quantity { get; set; }
        public decimal Amount { get; set; }
        public decimal AvgPrice { get; set; }
    }
}
